package com.shxc.smarttrade.other.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;

import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.other.model.SysConfigModel;
import com.shxc.smarttrade.other.model.UserInfoModel;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;

/**
 * 欢迎页
 */
@ContentView(R.layout.activity_welcome_c)
public class WelcomeActivity extends BaseActivity {
//    @ViewInject(R.id.entry_imageview)
//    ImageView entry_imageview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        hide();
        super.onCreate(savedInstanceState);

//        hostConfig();

        //根据用户类型进行别名设置
        if (AppUtils.isEmpty(spImp.getInviteCode())) {
            setMsgSetAlias("onLoginUser");
            Loger.e("Alias", "onLoginUser");
        } else {
            setMsgSetAlias(spImp.getInviteCode());
            Loger.e("Alias", spImp.getInviteCode());
        }
        sysConfig();


        if (spImp.getUserId() != -1 || SpUtils.getInt(mContext, "userId", -1) != -1) {
            showUserInfo();
        }
        if (MyApplication.tag == 1) {
            JumpTo(MainActivity.class);
            finish();
        } else {
//            scaleImage(this, entry_imageview, R.mipmap.welcome);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
//                    if (spImp.isFirstOpen()) {
//                        JumpTo(WelcomeGuideActivity.class);
//                        spImp.setFirstOpen(false);
//                        SpUtils.putBoolean(WelcomeActivity.this, "firstOpen", false);
//                    } else {
//                        JumpTo(MainActivity.class);
//                    }
                    JumpTo(MainActivity.class);
                    WelcomeActivity.this.finish();
                }
            }, 1000);
        }
    }

    /**
     * 屏蔽物理返回按钮
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public static void scaleImage(final Activity activity, final View view, int drawableResId) {

        // 获取屏幕的高宽
        Point outSize = new Point();
        activity.getWindow().getWindowManager().getDefaultDisplay().getSize(outSize);

        // 解析将要被处理的图片
        Bitmap resourceBitmap = BitmapFactory.decodeResource(activity.getResources(), drawableResId);

        if (resourceBitmap == null) {
            return;
        }

        // 开始对图片进行拉伸或者缩放

        // 使用图片的缩放比例计算将要放大的图片的高度
        int bitmapScaledHeight = Math.round(resourceBitmap.getHeight() * outSize.x * 1.0f / resourceBitmap.getWidth());

        // 以屏幕的宽度为基准，如果图片的宽度比屏幕宽，则等比缩小，如果窄，则放大
        final Bitmap scaledBitmap = Bitmap.createScaledBitmap(resourceBitmap, outSize.x, bitmapScaledHeight, false);

        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                //这里防止图像的重复创建，避免申请不必要的内存空间
                if (scaledBitmap.isRecycled())
                    //必须返回true
                    return true;


                // 当UI绘制完毕，我们对图片进行处理
                int viewHeight = view.getMeasuredHeight();


                // 计算将要裁剪的图片的顶部以及底部的偏移量
                int offset = (scaledBitmap.getHeight() - viewHeight) / 2;
                if (offset < 0) {
                    offset = 0;
                }

                // 对图片以中心进行裁剪，裁剪出的图片就是非常适合做引导页的图片了
                Bitmap finallyBitmap = Bitmap.createBitmap(scaledBitmap, 0, offset, scaledBitmap.getWidth(),
                        scaledBitmap.getHeight() - offset * 2);


                if (!finallyBitmap.equals(scaledBitmap)) {//如果返回的不是原图，则对原图进行回收
                    scaledBitmap.recycle();
                    System.gc();
                }

                // 设置图片显示
                view.setBackgroundDrawable(new BitmapDrawable(activity.getResources(), finallyBitmap));
                return true;
            }
        });
    }

    /**
     * 设置别名
     *
     * @param alias 别名
     */
    public void setMsgSetAlias(String alias) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }


    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.e("", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    if (msg.obj == null) {
                        Loger.e("obj == null", "!");
                    }
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String Logers;
            switch (code) {
                case 0:
                    Logers = "Set tag and alias success";
                    Loger.e("Welcome", Logers);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    Logers = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Loger.e("Welcome", Logers);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    Logers = "Failed with errorCode = " + code;
                    Loger.e("Welcome", Logers);
            }
        }
    };

    private void showUserInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        MyOkHttpUtils.getServiceDatas(map, Contents.ACCOUNT_SHOWUSERINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, UserInfoModel.class);
                    if (jam.isSuccess()) {
                        UserInfoModel model = (UserInfoModel) jam.getData();
                        if (model.getErr_code().equals("0")) {
                            spImp.setNick(model.getData().getNick());
                            spImp.setBirthday(model.getData().getBirthday());
                            spImp.setSex(model.getData().getSex());
//                            spImp.setInviteCode(model.getData().getTelphone());
                            spImp.setHeadUrl(model.getData().getHeadUrl());
                            spImp.setIntroduction(model.getData().getIntroduction());
                        }
                    } else {
                        Loger.e("error_msg",jam.getMsg());
//                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }



    /**
     * 开关
     * */
    private void sysConfig() {

        MyOkHttpUtils.getServiceDatas(null, Contents.SYSCONFIG, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, SysConfigModel.class);
                    if (jam.isSuccess()) {
                        SysConfigModel model = (SysConfigModel) jam.getData();
                        spImp.setDealSwitch(model.getData().getConfig().isDealSwitch());
                    } else {
                        ToastUtils.showToast("网络异常");
                    }
                }
                loadingDialog.dismiss();
            }
            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //隐藏状态栏
    public void hide() {
        Window window = getWindow();
        //定义全屏参数
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
        window.setFlags(flag, flag);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams winParams = window.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            window.setAttributes(winParams);
        }
    }

    /**
     * 开关
     * */
    private void hostConfig() {

        MyOkHttpUtils.getServiceDatas(null, Contents.HOSTCONFIG, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response",response);
                if (response != null) {
//                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, SysConfigModel.class);
//                    if (jam.isSuccess()) {
//                        SysConfigModel model = (SysConfigModel) jam.getData();
//                        spImp.setDealSwitch(model.getData().getConfig().isDealSwitch());
//                    } else {
//                        ToastUtils.showToast("网络异常");
//                    }
                }
            }
            @Override
            public void faild(Call call, Exception e, int id) {
                ToastUtils.showToast("网络异常");
                finish();
            }
        });
    }
}
